package com.ttx.pattern.example.chain.tomcat.filterchain;

import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;

/**
 * @author TimFruit
 * @date 19-5-12 上午8:54
 */
public class AppFilterConfig implements FilterConfig{

    /**
     * 过滤器链名字
     */
    private String name;
    private Map<String,String> paramMap;
    /**
     * 过滤器的类名
     */
    private String filterClass;
    private volatile  Filter filter;


    /**
     * Empty String collection to serve as the basis for empty enumerations.
     */
    private static final List<String> emptyString = Collections.emptyList();

    public AppFilterConfig(String name, String filterClass) {
        this.name = name;
        this.filterClass=filterClass;
    }

    public AppFilterConfig(String name,String filterClass, Map<String, String> paramMap) {
        this.name = name;
        this.filterClass=filterClass;
        this.paramMap = paramMap;
    }


    // --------------------------------------- filterConfig methods
    @Override
    public String getFilterName() {
        return this.name;
    }

    @Override
    public String getInitParameter(String name) {
        if(paramMap==null){
            return null;
        }
        if(paramMap.containsKey(name)){
            return paramMap.get(name);
        }
        return null;
    }

    @Override
    public Enumeration<String> getInitParameterNames() {
        if(paramMap==null){
            return Collections.enumeration(emptyString);
        }
        return Collections.enumeration(paramMap.keySet());

    }
    // ---------------------------------------


    Filter getFilter() throws ClassNotFoundException, IllegalAccessException, InstantiationException {

        if(filter==null){
            synchronized (AppFilterConfig.class){
                Class filterClazz=Class.forName(this.filterClass);
                Filter filter=(Filter) filterClazz.newInstance();

                filter.init(this);
                this.filter=filter;
            }
        }

        return filter;

    }


}
